#!/usr/bin/env python
#
#
#    Name: rpi-ir.py
#
#    Description: The rpi-ir daemon that will function as a listening interface
#                 for the IR sensor.
#
#    RPi-IR is a Raspberry Pi IR receiver project using the Sparkfun IR Breakout board + GPIO
#    Copyright (C) 2012  Adam Dosch <adam at wisehippy dot com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    RPi GPIO Information can be found at:
#
#         http://elinux.org/RPi_Low-level_peripherals#General_Purpose_Input.2FOutput_.28GPIO.29
#
#    Below is a snapshot of the GPIO Headpint out table from elinux.org:
#
#    ---------------------------------------
#    Raspberry Pi Header Pinout, top row:
#    ---------------------------------------
#     Pin Number	Pin Name	Hardware Notes	Alt 0 Function	Other Alternative Functions
#     P1-02	           5V0	 Supply through input poly fuse
#     P1-04	           DNC
#     P1-06	           GND
#     P1-08	           GPIO 14	 Boot to Alt 0 ->	 UART0_TXD	 ALT5 = UART1_TXD
#     P1-10	           GPIO 15	 Boot to Alt 0 ->	 UART0_RXD	 ALT5 = UART1_RXD
#     P1-12	           GPIO 18			 ALT4 SPI1_CE0_N ALT5 = PWM0
#     P1-14	           DNC
#     P1-16	           GPIO23			 ALT3 = SD1_CMD ALT4 = ARM_RTCK
#     P1-18	           GPIO24			 ALT3 = SD1_DATA0 ALT4 = ARM_TDO
#     P1-20	           DNC
#     P1-22	           GPIO25			 ALT4 = ARM_TCK
#     P1-24	           GPIO08		SPI0_CE0_N	
#     P1-26	           GPIO07		SPI0_CE1_N	
#   
#    ---------------------------------------
#     Header Pinout, bottom row:
#    ---------------------------------------
#     Pin Number	Pin Name	Hardware Notes	Alt 0 Function	Other Alternative Functions
#     P1-01	           3.3 V	 50 mA max current draw
#     P1-03	           GPIO 0	 1K8 pull up resistor	 I2C0_SDA	 I2C0_SDA
#     P1-05	           GPIO 1	 1K8 pull up resistor	 I2C0_SCL	 I2C0_SCL
#     P1-07	           GPIO 4			 GPCLK0
#     P1-09	           DNC
#     P1-11	           GPIO17			 ALT3 = UART0_RTS, ALT5 = UART1_RTS
#     P1-13	           GPIO21		 PCM_DIN	 ALT5 = GPCLK1
#     P1-15	           GPIO22			 ALT3 = SD1_CLK ALT4 = ARM_TRST
#     P1-17	           DNC
#     P1-19	           GPIO10		SPI0_MOSI	
#     P1-21	           GPIO9		SPI0_MISO	
#     P1-23	           GPIO11		SPI0_SCLK	
#     P1-25	           DNC
#   
#    ---------------------------------------
#     Colour legend
#    ---------------------------------------
#     +5 V
#     +3.3 V
#     Ground, 0V
#     Do not connect
#     UART
#     GPIO
#     SPI
#     I?C
#
#
########################################################################################
# Change    Date        Name            Description
########################################################################################
#  001      07-08-2012  Adam Dosch      Initial Release, so far, no scope, using to
#                                       create pulse map for controller buttons from a
#                                       Vizio remote.  NO PRODUCTION CODE AT ALL!
#
########################################################################################

import ConfigParser
import sys
import os
import time

try:
    import ircodes
except ImportError:
    print "Add cwd of 'ircodes.py' to PYTONPATH in your environment, re-source and re-run!"
    sys.exit(1)
    
try:
    import RPi.GPIO as GPIO
except ImportError:
    print "Need RPi to continue.  Download from: http://pypi.python.org/pypi/RPi.GPIO"
    sys.exit(1)


MAXPULSE = 800
PULSETIME = 40

###pulsecollection = []
testcollection = []

def usleep(ms):
    time.sleep(float(ms/1000000))

def print_pulses(l):
    for items in l:
        print items

def captureIR():
    while(1):
        # Setting initial values
        currentpulse = 0

        
        while True:
            # Setting initial values
            highpulse = 0
            lowpulse = 0
            
            while GPIO.input(17) == True:
                #print "Pin is high"
                highpulse = highpulse + 1
                #print "highpulse:", highpulse
                #print "usleep for ", PULSETIME
                usleep(PULSETIME)
            
                if ((highpulse >= MAXPULSE) and (currentpulse != 0)):
                    #print "Reset on high?"
                    #print_pulses(pulsecollection)
                    #currentpulse = 0
                    return currentpulse
            
            ###if currentpulse == 0:
            ###    pulsecollection.append((0, currentpulse, 0))
            ###else:
            ###    pulsecollection.append((0, currentpulse, highpulse*PULSETIME))
            
            while GPIO.input(17) == False:
                #print "Pin is low"
                lowpulse = lowpulse + 1
                #print "lowpulse:", lowpulse
                
                #print "usleep for ", PULSETIME
                usleep(PULSETIME)
                
                if ((lowpulse >= MAXPULSE) and (currentpulse != 0)):
                    #print_pulses(pulsecollection)
                    #print "Reset on low?"
                    #currentpulse = 0
                    return currentpulse 
            
            ###pulsecollection.append((1, currentpulse, lowpulse*PULSETIME))
            
            if currentpulse == 0:
                testcollection.append((0, lowpulse*PULSETIME))
            else:
                testcollection.append((highpulse*PULSETIME, lowpulse*PULSETIME))
                
            currentpulse = currentpulse + 1

def match_ircodes(pulsecollection):
    pass

def main():
        
    try:
        Config = ConfigParser.ConfigParser()
        
        # Config file exist?
        if os.path.isfile(os.getcwd() + "/rpiir.conf"):
            Config.read(os.getcwd() + "/rpiir.conf")
            
        
        # Setting pinout map to follow - using Broadcom pin reference
        GPIO.setmode(GPIO.BCM)
        
        # Using BCM GPIO pin 17, set direction to 'input'
        GPIO.setup(17, GPIO.IN)
        
        pulsecount = captureIR()
    
        print "Received", pulsecount, "-long pulse:"
        print "======="
        print testcollection
        print "======="
        
        result = match_ircodes(testcollection)
        
    except KeyboardInterrupt:
        print "Bailing, SIGINT sent!"
        print_pulses(pulsecollection)
        sys.exit(1)   

if __name__ == '__main__':
    main()

    

